package sms

import (
	"encoding/json"
	"net/http"

	log "github.com/Sirupsen/logrus"
)
import "net/url"

var (
	yunpianUrl = "http://yunpian.com/v1/sms/send.json"
	//apikey     = "131eea1125417e3ec48cfe5dec484a26"
)

type YunpianService struct {
	apikey string
}

func NewYunpianService(apiKey string) SmsService {
	return &YunpianService{apikey: apiKey}
}

func (yunpian *YunpianService) Send(phone PhoneNumber, message string) (err error) {
	if !phone.Valid() {
		return InvalidPhoneNumberError{PhoneNumber: string(phone)}
	}
	postData := make(url.Values)
	postData.Set("apikey", yunpian.apikey)
	postData.Set("mobile", string(phone))
	postData.Set("text", message)
	resp, err := http.PostForm(yunpianUrl, postData)
	if err != nil {
		log.Errorln(err)
		return err
	}
	data := make(map[string]interface{})
	retReader := json.NewDecoder(resp.Body)
	err = retReader.Decode(&data)
	if err != nil {
		log.Errorln(err)
		return err
	}
	log.Println(data)
	if code, ok := data["code"]; ok {
		if codeInt, ok := code.(int); ok && codeInt != 0 {
			log.Errorln(data)
			return ResponseError
		}
	} else {
		log.Errorln(data)
		return ResponseError
	}
	return nil
}
